package com.haikesi.api.device.service.impl;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.haikesi.api.base.*;
import com.haikesi.api.base.Error;
import com.haikesi.api.device.dao.DeviceDao;
import com.haikesi.api.device.domain.po.DevicePO;
import com.haikesi.api.device.domain.vo.*;
import com.haikesi.api.device.service.IDeviceService;
import com.haikesi.api.subscribertable.dao.SubscriberTableDao;
import com.haikesi.api.subscribertable.domain.po.SubscriberTablePo;
import com.haikesi.exception.BusinessException;
import com.haikesi.util.ApcosApiUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;


@Service
@Transactional
public class DeviceServiceImpl implements IDeviceService {
    private static Log log = LogFactory.getLog(DeviceServiceImpl.class);

    @Autowired
    DeviceDao dao;

    @Autowired
    private SubscriberTableDao subscriberTableDao;


    @Override
    public List<DeviceVO> getList(DeviceSearchVO searchVO) {
        DevicePO po = new DevicePO();
        if(po.getUser()==null){
            searchVO.setOrganizationId("");
            return dao.getList(searchVO);
        }
        searchVO.setOrganizationId(po.getUser().getOrganizationId());
        if(po.getUser().getIsAdmin()==1){
            searchVO.setOrganizationId("999");
        }
        return dao.getList(searchVO);
    }

    @Override
    public void update(DeviceUpdateVO updateVO) {
        DevicePO po = new DevicePO();
        BeanUtils.copyProperties(updateVO, po);
        po.preUpdate();
        int i = dao.updateByPrimaryKeySelective(po);
        if (i == Constants.SQL_RETUN_SUCCESS) {
            throw new BusinessException(Type.EXCEPTION_FAIL);
        }
    }

    @Override
    public int importApcosDervice(String account) {
        Example example = new Example(SubscriberTablePo.class);
        example.and().andEqualTo("subscriberNumber", account);
        SubscriberTablePo subscriberTablePo = subscriberTableDao.selectOneByExample(example);
        if (subscriberTablePo==null) {
            throw new BusinessException(Type.EXIST_ERROR, ErrorTools.ErrorAsArrayList(new Error("subscriberNumber", "订阅账号不已存在")));
        }
        if(subscriberTablePo.getSubscriberState()==Constants.SUBSCRIBER_STATE_0){
            throw new BusinessException(Type.EXIST_ERROR, ErrorTools.ErrorAsArrayList(new Error("subscriberNumber", "未订阅的账号不能同步设备")));
        }
        Long lastCreatTime=1488606363L;
        if(subscriberTablePo.getLastCreatTime()!=null){
            lastCreatTime=subscriberTablePo.getLastCreatTime().getTime();
        }
        subscriberTablePo.preUpdate();
        if(subscriberTablePo.getSubscriberState()==Constants.SUBSCRIBER_STATE_1){
            subscriberTablePo.setSubscriberState(Constants.SUBSCRIBER_STATE_2);
        }
        //获取平台接口
        String jsonData=ApcosApiUtils.getDevice(subscriberTablePo.getSubscriberNumber(),lastCreatTime);
        //String jsonData= "{\"deviceList\":[]}" ;
        if(StringUtils.isBlank(jsonData)){
            subscriberTableDao.updateByPrimaryKeySelective(subscriberTablePo);
            return 0;
        }
        JSONObject object=JSONObject.parseObject(jsonData);
        JSONArray deviceList= (JSONArray) object.get("deviceList");
        if(deviceList.size()>0) {
            //添加设备列表
            for (Object device : deviceList) {
                DevicePO po = new DevicePO();
                JSONObject one = (JSONObject) device;

                Example sexample = new Example(DevicePO.class);
                sexample.and().andEqualTo("deviceSubscriberNumber", account).andEqualTo("deviceMac",one.get("device_mac").toString());
                List<DevicePO> list=dao.selectByExample(sexample);
                if(list==null||list.size()==0){
                    po.setDeviceMac(one.get("device_mac").toString());
                    po.setSerialNum(one.get("serial_num").toString());
                    po.setProductCode(one.get("product_code").toString());
                    po.setDeviceName(one.get("device_name").toString());
                    po.setDeviceAlias(po.getDeviceName());
                    po.setOrganizationId(subscriberTablePo.getOrganizationId());
                    po.setDeviceSubscriberId(subscriberTablePo.getId());
                    po.setDeviceSubscriberNumber(subscriberTablePo.getSubscriberNumber());
                    po.preInsert();
                    dao.insertSelective(po);
                }
            }
            //更新订阅账号获取时间
            Long lastCreatTimes = (Long) object.get("lastCreatTime");
            subscriberTablePo.setLastCreatTime(new Date(lastCreatTimes));
        }
        subscriberTableDao.updateByPrimaryKeySelective(subscriberTablePo);
        return deviceList.size();
    }

    @Override
    public void controlDervice(DeviceControlVO deviceControlVO) {
        if(StringUtils.isNotBlank(deviceControlVO.getSerial_mac())){
            deviceControlVO.setSerial_mac(deviceControlVO.getSerial_mac());
        }
        String code= ApcosApiUtils.sendDeviceCmd(deviceControlVO.getAccount(),deviceControlVO.getSerial_num(),deviceControlVO.getOperation(),deviceControlVO.getControlParams(),deviceControlVO.getProductId());
        if("0000".equals(code)){
            return;
        }
        if("0001".equals(code)){
            throw new BusinessException(Type.EXCEPTION_FAIL, ErrorTools.ErrorAsArrayList(new Error("controlDervice", "操作失败,请稍后在试")));
        }
        if("9999".equals(code)){
            throw new BusinessException(Type.PARAM_VALIDATE_FAIL, ErrorTools.ErrorAsArrayList(new Error("controlDervice", "参数校验失败")));
        }
    }

    @Override
    public void batch_up_position(DeviceBatchUpdateVO updateVO) {
        DevicePO po = new DevicePO();
        po.setPositionId(updateVO.getId());
        for (String deviceId:updateVO.getDeviceIds()) {
            po.setId(deviceId);
            po.preUpdate();
            dao.updateByPrimaryKeySelective(po);
        }
    }

    @Override
    public void batch_up_organization(DeviceBatchUpdateVO updateVO) {
        DevicePO po = new DevicePO();
        po.setOrganizationId(updateVO.getId());
        for (String deviceId:updateVO.getDeviceIds()) {
            po.setId(deviceId);
            po.preUpdate();
            dao.updateByPrimaryKeySelective(po);
        }
    }

    @Override
    public R controlDervice_s(DeviceControlVO deviceControlVO) {
        if(StringUtils.isNotBlank(deviceControlVO.getSerial_mac())){
            deviceControlVO.setSerial_mac(deviceControlVO.getSerial_mac());
        }
       return ApcosApiUtils.sendDeviceCmd_s(deviceControlVO.getAccount(),deviceControlVO.getSerial_num(),deviceControlVO.getOperation(),deviceControlVO.getControlParams(),deviceControlVO.getProductId());
    }

    @Override
    public void deleteBySerialNum(String id, String account) {
        if(StringUtils.isBlank(id)||StringUtils.isBlank(account)){
            return;
        }
        Example example = new Example(DevicePO.class);
        example.and().andEqualTo("deviceSubscriberNumber", account).andEqualTo("serialNum",id);
        dao.deleteByExample(example);
    }


}
